package org.pragma;

import java.util.ArrayList;
import java.util.List;

import org.pragma.objects.PragmaObject;
import org.w3c.dom.Element;

public class PragmaCall extends PragmaObject {

	PragmaReference callee;
	PragmaObject calleeObject;
	List<PragmaObject> parameters = new ArrayList<PragmaObject>();
	String methodName;
	
	public PragmaCall setCalle(PragmaObject pragmaObject) {
		if (pragmaObject instanceof PragmaReference){
			callee = (PragmaReference)pragmaObject;
		}else{
			calleeObject = pragmaObject;
		}
		return this;
	}

	public PragmaCall setMethod(String string) {
		methodName = string;
		return this;
	}

	/*public PragmaCall setParameters(PragmaList<PragmaObject> parameters) {
		this.parameters = parameters;
		return this;
	}*/
	
	
	
	public PragmaObject execute(PragmaContext ctx) throws Exception{
		PragmaObject result = null;
		if(calleeObject==null){
			calleeObject =  ctx.findObject(callee);
		}
		System.out.println(ctx+" "+callee.getName()+"."+methodName+"("+parameters+")");
		
		result = calleeObject.execute(ctx,methodName,parameters);
		
		return result;
	}
	
	
	public PragmaCall addParameter(PragmaObject obj) {
		parameters.add(obj);
		return this;
	}
	
	public String toString(){
		return callee+"."+methodName +"("+parameters+")";
		
	}
	
	public String display(String margin){
		String result = "";
		result = margin+callee+"."+methodName +"(\n";
		for(PragmaObject call:parameters){
			result += call.display(margin+"  ")+"\n";
		}
		result+=margin+")";
		return result;
	}

	public PragmaCall load(Element elem) {
		if(elem.getAttribute("callee")!=null){
			callee = new PragmaReference(elem.getAttribute("callee"));
		}
		return this;
	}

	
}
